package com.huangxt.test.tree;


import java.util.*;

public class TreeJson {
    private Map<String,TreeJson> map ;
    private String id;
    private String text;


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Map<String, TreeJson> getMap() {
        return map;
    }

    public void setMap(Map<String, TreeJson> map) {
        this.map = map;
    }

    public TreeJson(String id, String text) {
        this.id = id;
        this.text = text;
    }

    public TreeJson() {
    }

    public String toString(){
        String ext = ",state='";
        if (map==null||map.isEmpty()){
            ext += "opened'";
        }else{
            ext +="closed',children="+map.values().toString();
        }
        return "{ id='" + id+ "', text='" + text + "'"+ext+"}";
    }
    public String getState(){
        if(map==null||map.isEmpty()){
            return "opened";
        }
        return "closed";
    }
    public void addChild(TreeJson treeJson){
        if(map==null||!map.containsKey(treeJson.getId())){
            if(map==null){
                map = new HashMap<>(10);
            }
            map.put(treeJson.getId(),treeJson);


        }else {
            if(treeJson.getMap().values().isEmpty())
                return;
            for (TreeJson tempTreeJson:treeJson.getMap().values()){
                if(treeJson.getId().equalsIgnoreCase(tempTreeJson.getId())){
                    for (TreeJson childTreeJson:treeJson.getMap().values()){
                        tempTreeJson.addChild(childTreeJson);
                    }
                }
            }
        }
    }
    public boolean existsIds(String ... ids){
        TreeJson treeJsonTemp = this;
        try {
            for (String id:ids){
                treeJsonTemp = this.getMap().get(id);
            }

        } catch (Exception e) {
            return false;
        }
        return treeJsonTemp!=null;
    }
    public void addChild(TreeJson treeJson,String ... ids){
        TreeJson treeJsonTemp = this;
        try {
            for (String id:ids){
                treeJsonTemp = this.getMap().get(id);
            }
            treeJsonTemp.addChild(treeJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addChildren(List<TreeJson> treeJsons){
        if(treeJsons==null&&treeJsons.isEmpty())
            return;
        for (TreeJson treeJson:treeJsons){
            this.addChild(treeJson);
        }
    }

}
